%% This code reproduces Table 2.

clear;
final = cell(14,5);

FF = [1 3 4 5 6];

for i = 1:5

    load(['B005/Result_K_',num2str(FF(i)) '.mat'])

    for k = 1:FF(i)
   
        arr{i,k}   = [k, FF(i) + 2*k-1, FF(i) + 2*k];
        arr_J{i,k} = [FF(i) + 2*k-1, FF(i) + 2*k];

        % Ensure formatting for the chi2cdf calculations
        H = [1,-1, 0; 1, 0, -1];
        chi2_value_full = 1 - chi2cdf((H*Lambda_hat_AJX(:,arr{i,k})')'*inv(H*Vn_AJX(arr{i,k},arr{i,k})*H')*((H*Lambda_hat_AJX(:,arr{i,k})')), 2);
        
        R = [1,-1];
        chi2_value_partial = 1 - chi2cdf((R*Lambda_hat_AJX(:,arr_J{i,k})')'*inv(R*Vn_AJX(arr_J{i,k},arr_J{i,k})*R')*(R*Lambda_hat_AJX(:,arr_J{i,k})'), 1);

        % Check if the p-values are less than 0.001, otherwise format with 3 decimal places
        if FF(i)~=4
            if chi2_value_full < 0.001
                final(2*k-1,i) = {'<0.001'};
            else
                final(2*k-1,i) = {sprintf('%.3f', chi2_value_full)};
            end

            if chi2_value_partial < 0.001
                final(2*k,i) = {'<0.001'};
            else
                final(2*k,i) = {sprintf('%.3f', chi2_value_partial)};
            end

        elseif k ~= 4
            if chi2_value_full < 0.001
                final(2*k-1,i) = {'<0.001'};
            else
                final(2*k-1,i) = {sprintf('%.3f', chi2_value_full)};
            end

            if chi2_value_partial < 0.001
                final(2*k,i) = {'<0.001'};
            else
                final(2*k,i) = {sprintf('%.3f', chi2_value_partial)};
            end

        else
            if chi2_value_full < 0.001
                final(11,i) = {'<0.001'};
            else
                final(11,i) = {sprintf('%.3f', chi2_value_full)};
            end

            if chi2_value_partial < 0.001
                final(12,i) = {'<0.001'};
            else
                final(12,i) = {sprintf('%.3f', chi2_value_partial)};
            end
        end
    end

    arr_C{i} = [1:FF(i)]; 
    chi2_value_C = 1 - chi2cdf(Lambda_hat_AJX(:,arr_C{i})*inv(Vn_AJX(arr_C{i},arr_C{i}))*Lambda_hat_AJX(:,arr_C{i})', FF(i));
    if chi2_value_C < 0.001
                
        final(13,i) = {'<0.001'};
    
    else
    
        final(13,i) = {sprintf('%.3f', chi2_value_C)};
    
    end


    arr_AJ{i} = [(FF(i)+1):3*FF(i)]; 
    chi2_value_AJ = 1 - chi2cdf(Lambda_hat_AJX(:,arr_AJ{i})*inv(Vn_AJX(arr_AJ{i},arr_AJ{i}))*Lambda_hat_AJX(:,arr_AJ{i})', 2*FF(i));
    if chi2_value_AJ < 0.001
                
        final(14,i) = {'<0.001'};
    
    else
    
        final(14,i) = {sprintf('%.3f', chi2_value_AJ)};
    
    end


end

T = cell2table(final);
writetable(T, '15min_Tests_B005.csv')
  
